package Singleton;

//Lazy Singleton pattern.
public class LazySingleton {
    // volatile 防止 指令重排，和JMM的内存不可见
    private volatile static LazySingleton instance = null;
    private LazySingleton(){
        // anti-reflection
        if(instance != null){
            throw new RuntimeException("Use getInstance() to get an instance");
        }
    }

    public static LazySingleton getInstance() {
        // 判断有无必要加锁
        if(instance == null){
            synchronized(LazySingleton.class){
                // 判断是否需要创建懒汉实例
                if(instance == null){
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}
